package com.jiangyg.mall.gateway.filter;

import com.jiangyg.mall.core.support.env.EnvConstant;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.gateway.constant.GatewayConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 类描述：网关全局请求过滤器
 *
 * @author jiangyg
 * @version 4.0
 * @date 2021-12-28
 */
@Slf4j
@Component
public class RequestGlobalFilter implements GlobalFilter, Ordered, InitializingBean {

    /**
     * 安全认证参数名
     */
    private String securityHeader;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 清除请求头中的安全认证参数
        final ServerHttpRequest mutateRequest = exchange.getRequest().mutate().headers(headers -> headers.remove(securityHeader)).build();
        final ServerWebExchange mutateExchange = exchange.mutate().request(mutateRequest).build();
        // TODO 去除 安全认证的用户信息
        return chain.filter(mutateExchange);
    }

    @Override
    public void afterPropertiesSet() {
        // TODO 待实现此逻辑
        this.securityHeader = EnvConstant.getString(GatewayConstant.GATEWAY_SECURITY_HEADER);
        Logger.debug(log, () -> String.format("获取内网认证参数[%s]", this.securityHeader));
//        if (StringUtils.isBlank(securityHeader)) {
//            throw new CoreException("网关全局请求过滤器初始化失败：没有获取到安全认证参数！");
//        }
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }

}




